package com.example.user

import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import androidx.appcompat.app.AppCompatActivity
import com.example.network.CheckResultListenerAddresponseLogin
import com.example.network.ResponseLoginBean
import com.example.network.SendRequest
import com.example.user.R

class LoginActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var registerButton: TextView
    private lateinit var resetButton: TextView
    private lateinit var etUsername: EditText
    private lateinit var etPassword: EditText
    private lateinit var btnTogglePassword: ImageButton
    private lateinit var loginButton: Button
    private lateinit var checkBoxAgreement: CheckBox
    private var isPasswordVisible = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.login_activity)

        //为注册按钮添加监听器
        registerButton = findViewById(R.id.txt_register)
        registerButton.setOnClickListener(this)

        //为修改密码按钮添加监听器
        resetButton = findViewById(R.id.txt_forget)
        resetButton.setOnClickListener(this)

        //为登录按钮添加监听器
        loginButton = findViewById(R.id.btn_login)
        loginButton.isEnabled = false // 默认禁用登录按钮
        loginButton.setOnClickListener(this)

        // 初始化用户协议复选框
        checkBoxAgreement = findViewById(R.id.check_box_agreement)
        checkBoxAgreement.setOnCheckedChangeListener { _, isChecked ->
            // 根据复选框状态启用/禁用登录按钮
            loginButton.isEnabled = isChecked
        }

        //为登录界面的返回按钮添加监听器
        val backMainButton: ImageView = findViewById(R.id.title_bar_back)
        backMainButton.setOnClickListener(this)

        //为登录editText进行注册
        etUsername = findViewById(R.id.Username)

        //为密码editText进行注册
        etPassword = findViewById(R.id.PassWord)

        //初始化密码显示/隐藏按钮
        btnTogglePassword = findViewById(R.id.btn_toggle_password)
        btnTogglePassword.setOnClickListener(this)

        //设置密码输入框默认隐藏密码
        etPassword.transformationMethod = PasswordTransformationMethod.getInstance()
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.btn_login -> {
                Log.d("tag", "当前输入的账号为${etUsername.text.toString()}")
                // 对输入进行检测
                val etusername = etUsername.text.toString().trim()
                val etpassword = etPassword.text.toString().trim()
                if (etusername.isEmpty() || etpassword.isEmpty()) {
                    Toast.makeText(this@LoginActivity, "请输入正确的账号和密码", Toast.LENGTH_SHORT).show()
                } else if (etusername != null && etusername.matches("^1\\d{10}$".toRegex())) {
                    SendRequest.loginUser(etusername, etpassword, object : CheckResultListenerAddresponseLogin {
                        override fun onSuccess(desc: ResponseLoginBean) {
                            Toast.makeText(this@LoginActivity, desc.getResultDesc(), Toast.LENGTH_SHORT).show()
                            // 保存用户信息到SharedPreferences
                            val preferences: SharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE)
                            val editor = preferences.edit()
                            editor.putString("username", desc.getUsername())
                            editor.putString("phone", desc.getPhone())
                            editor.putString("token", desc.getToken())
                            editor.putBoolean("is_login", true)
                            editor.apply()
                            finish()
                        }

                        override fun onFail(msg: String) {
                            Toast.makeText(this@LoginActivity, msg, Toast.LENGTH_SHORT).show()
                        }
                    })
                } else {
                    Toast.makeText(this@LoginActivity, "帐号错误", Toast.LENGTH_SHORT).show()
                }
            }
            R.id.txt_register -> {
                startActivity(Intent(this, RegisterActivity::class.java))
            }
            R.id.txt_forget -> {
                startActivity(Intent(this, ResetActivity::class.java))
            }
            R.id.title_bar_back -> {
                finish()
            }
            R.id.btn_toggle_password -> {
                togglePasswordVisibility()
            }
        }
    }

    /**
     * 切换密码的显示和隐藏状态
     */
    private fun togglePasswordVisibility() {
        if (isPasswordVisible) {
            // 隐藏密码
            etPassword.transformationMethod = PasswordTransformationMethod.getInstance()
            btnTogglePassword.setImageResource(R.drawable.ic_password_eye_off)
        } else {
            // 显示密码
            etPassword.transformationMethod = HideReturnsTransformationMethod.getInstance()
            btnTogglePassword.setImageResource(R.drawable.ic_password_eye_on)
        }

        // 切换状态标志
        isPasswordVisible = !isPasswordVisible

        // 将光标移到文本末尾
        etPassword.setSelection(etPassword.text.length)
    }
}